import {defineStore} from "pinia";
import {doGet} from "@/config/http";
import {svc} from '@/config/common'

const useDictStore = defineStore(
    'dict',
    {
        state: () => ({
            dicts: {}
        }),
        actions: {
            getDicts(dictType) {
                if (!dictType) {
                    return null
                }
                if (this.dicts[dictType] !== undefined) {
                    return this.dicts[dictType]
                }
                this.initDicts(dictType)
                return this.dicts[dictType]
            },
            setDicts(key, value) {
                if (key !== null && key !== "") {
                    // this.dict.push({
                    //     key: key,
                    //     value: value
                    // });
                    this.dicts[key] = value
                }
            },
            initDicts(dictType) {
                if (dictType === 'yesOrNo') {
                    this.dicts[dictType] = []
                    this.dicts[dictType].push({key: "1", value: "是"})
                    this.dicts[dictType].push({key: "0", value: "否"})
                }
                if (this.dicts[dictType] !== undefined) {
                    return
                }
                doGet(svc, '/dict-value/listByField', {field: 'dictType', values: dictType}, false).then(res => {
                    this.dicts[dictType] = []
                    if (res && res.length > 0) {
                        res.map(item => {
                            let k = item.dictKey
                            let v = item.dictValue
                            this.dicts[dictType].push({key: k, value: v})
                        })
                    }
                })
            },
            initAllDicts() {
                doGet(svc, '/dict-value/listByField', {field: 'state', values: '1'}, false).then(res => {
                    if (res.length > 0) {
                        res.map(item => {
                            let type = item.dictType
                            let k = item.dictKey
                            let v = item.dictValue
                            let elTagType = item.elTagType
                            let elTagClass = item.elTagClass
                            let elTagStyle = item.elTagStyle
                            if (!this.dicts[type]) {
                                this.dicts[type] = []
                            }
                            this.dicts[type].push({key: k, value: v, elTagType, elTagClass, elTagStyle})
                        })
                        console.debug('dicts', this.dicts)
                    }
                })
            },
        }
    })

export default useDictStore
